package com.example.util;

import com.example.mapper.SysRoleMapper;
import com.example.model.UserInfo;
import com.example.impl.UserInfoServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class WfxRealm extends AuthorizingRealm {

    @Autowired
    private UserInfoServiceImpl userInfoService;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

//        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

////            当结合系统来完成授权的功能时，当前登录的用户，需要从数据库中查询出它的 角色列表和权限列表
////                授权的思路：
////                    1.先根据当前登录的用户ID，查询出他所具备的角色列表
////                        * 将查询出来的角色列表（角色标识。通常不允许出来中文）(角色标识：roleFlag)
//        //获取当前登录的用户信息
//        UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
//        //根据用户的ID，查询它具备的角色列表
//        List<SysRole> roleList = sysRoleService.findRoleListByUserId(userInfo.getUserId());
////
////                    2.如果有权限的设置，还要根据用户ID查询用户的权限列表
//        //下面这步操作，是将当前用户的角色列表添加shiro会话中
//        for (SysRole sysRole : roleList) {
//            authorizationInfo.addRole(sysRole.getRoleFlag());
//        }


//        return authorizationInfo;


      UserInfo user = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        //1.获得授权用户信息
//        TbUsers user = (TbUsers) principalCollection.iterator().next();
//        Long userId= user.getId();
//
//        //2.通过user的id查询当前用户的所有角色名
        Set<String> roles = sysRoleMapper.finRoleByAccount(user.getAccount());
//
        Set<String> permissions = sysRoleMapper.findModuleByAccount(user.getAccount());
//
//        //3.通过user的id查询当前用户的所有权限percode
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

//        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//        //根据用户名查询用户对象信息
//        UserInfo userInfo = userInfoService.findUserInfoByUserName(token.getUsername());
//        if (userInfo == null) {
//            return null;
//        }
//        // 直接将其封装为 返回的数据类型
//        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userInfo, userInfo.getPassword(), ByteSource.Util.bytes(userInfo.getAccount()), getName());
//        return authenticationInfo;

        //1.从token中获取用户名
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = new String(token.getPassword());
//
//        String md5Pwd = new SimpleHash("MD5",password).toHex();
        String md5Pwd = new SimpleHash("md5",password,ByteSource.Util.bytes(username),56).toHex();
        //2.根据用户名查询数据库(UserDAO)
        UserInfo user = (UserInfo) userInfoService.findUserInfoByUserName(username);

        if (user == null){
            throw new UnknownAccountException("账号不存在");
        }else{
            //用户存在则验证密码
            if ( !user.getPassword().equals(md5Pwd)){
                throw new IncorrectCredentialsException("密码错误");
            }
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getAccount()), getName());
    }
}
